Ch1. 타입
타입이란 자바스크립트 엔진, 개발자 모두에게 어떤 값을 다른 값과 분별할 수 있는, 고유한 내부 특성의 집합이다.
즉, 기계와 사람이 24와 "24"를 다르게 처리한다면 두 값의 타입은 서로 다르다.
1.1 타입, 그 실체를 이해하자
- 타입이 명확하지 않다.
- 어떤 타입으로든 형 변환이 일어난다.
- 실체를 이해해야 예측 가능하다.
1.2 내장 타입
자바스크립트에는 7개의 내장 타입이 있다:
nullundefinednumberbooleanstringobjectsymbol
object를 제외한 나머지는 "원시 타입(primitive type)"이라 한다.
typeof 연산자로 확인할 수 있다:
typeof undefined === 'undefined' // true
typeof true === 'boolean' // true
typeof 42 === 'number' // true
typeof "42" === 'string' // true
typeof { life: 42 } === 'object' // true
typeof Symbol() === 'symbol' // true
typeof function a() {} === 'function' // true
typeof [1, 2, 3] === 'object' // true
typeof null === 'object' // true
null...?
typeof null은'object'- 레거시 이슈로 인해 고치지 못하고 있음
- 체크 방법:
if (!a && typeof a === 'object') {
// a는 null
}
falsy 값들
0-0false""(빈 문자열)nullundefinedNaN
truthy 값들
- falsy를 제외한 모든 값
→ 빈 배열도 truthy임
function...?
typeof로 확인하면'function'- 정확히는 호출 가능한 object
- 내부에
[[Call]]프로퍼티가 있는 객체 length는 매개변수 개수
const fn = function(a, b) {};
console.log(fn.length); // 2
typeof vs instanceof
typeof
- 값의 기본형을 문자열로 반환
instanceof
__proto__를 기준으로 비교
const TestObj = function () {};
const TestObj2 = function () {};
const testObj = new TestObj();
console.log(typeof testObj); // 'object'
console.log(testObj instanceof Object); // true
console.log(testObj instanceof TestObj); // true
console.log(testObj instanceof TestObj2); // false
1.3 값은 타입을 가진다
- 변수는 타입이 없고, 값이 타입을 가진다
- 변수는 언제든 다른 타입으로 변경 가능